<script lang="ts" setup>
import { reactive, ref, computed, nextTick } from "vue"
import { type FormInstance, type FormRules } from "element-plus"
import { createHolidayApi, updateHolidayApi } from "@/api/calculator"

interface FormData {
  holiday_name: string
  start_date: string
  end_date: string
  is_workday: number
  holiday_type: string
}

interface OpenOptions {
  id?: number | string
  initialData?: Partial<FormData>
}

interface Emits {
  (e: "submit", data: { id?: number | string } & FormData): void
}

const emit = defineEmits<Emits>()

// 内部状态
const formRef = ref<FormInstance | null>(null)
const visibleRef = ref(false)
const currentUpdateId = ref<number | string | undefined>(undefined)

const formData = reactive<FormData>({
  holiday_name: "",
  start_date: "",
  end_date: "",
  is_workday: 0,
  holiday_type: ""
})

const formRules: FormRules = reactive({
  holiday_name: [{ required: true, trigger: "blur", message: "请输入节假日名称" }],
  start_date: [{ required: true, trigger: "change", message: "请选择开始日期" }],
  end_date: [{ required: true, trigger: "change", message: "请选择结束日期" }],
  holiday_type: [{ required: true, trigger: "blur", message: "请输入类型" }]
})

const resetForm = () => {
  formData.holiday_name = ""
  formData.start_date = ""
  formData.end_date = ""
  formData.is_workday = 0
  formData.holiday_type = ""
  formRef.value?.clearValidate()
}

// 关闭弹窗
const handleClose = () => {
  visibleRef.value = false
}

// 对话框真正关闭后触发（重置表单）
const handleDialogClosed = () => {
  resetForm()
  currentUpdateId.value = undefined
}

const handleSubmit = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) {
      console.error("表单校验不通过", fields)
      return
    }
    const payload = {
      holiday_name: formData.holiday_name,
      start_date: formData.start_date,
      end_date: formData.end_date,
      is_workday: formData.is_workday,
      holiday_type: formData.holiday_type
    }
    if (currentUpdateId.value !== undefined) {
      const id = currentUpdateId.value as number | string
      updateHolidayApi({
        holiday_id: id,
        ...payload
      })
        .then(() => {
          emit("submit", { id, ...payload })
          handleClose()
        })
        .catch((err: any) => {
          console.error("更新失败", err)
        })
    } else {
      createHolidayApi(payload)
        .then(() => {
          emit("submit", payload)
          handleClose()
        })
        .catch((err: any) => {
          console.error("新增失败", err)
        })
    }
  })
}

// 暴露给父组件：打开
const open = (options?: OpenOptions) => {
  currentUpdateId.value = options?.id
  formData.holiday_name = options?.initialData?.holiday_name ?? ""
  formData.start_date = options?.initialData?.start_date ?? ""
  formData.end_date = options?.initialData?.end_date ?? ""
  formData.is_workday = options?.initialData?.is_workday ?? 0
  formData.holiday_type = options?.initialData?.holiday_type ?? ""
  visibleRef.value = true
  nextTick(() => formRef.value?.clearValidate())
}

// 暴露给父组件：关闭
const close = () => {
  handleClose()
}

const isEdit = computed(() => currentUpdateId.value !== undefined)
const dialogTitle = computed(() => (isEdit.value ? "修改节假日" : "新增节假日"))

defineExpose({
  open,
  close,
  submit: handleSubmit,
  reset: resetForm
})
</script>

<template>
  <el-dialog
    :model-value="visibleRef"
    :title="dialogTitle"
    @update:model-value="handleClose"
    @close="handleDialogClosed"
    width="40%"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
      <el-form-item prop="holiday_name" label="节假日名称">
        <el-input v-model="formData.holiday_name" placeholder="请输入" />
      </el-form-item>
      <el-form-item prop="holiday_type" label="类型">
        <el-input v-model="formData.holiday_type" placeholder="请输入 如：法定假日/调休 等" />
      </el-form-item>
      <el-form-item prop="start_date" label="开始日期">
        <el-date-picker v-model="formData.start_date" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" />
      </el-form-item>
      <el-form-item prop="end_date" label="结束日期">
        <el-date-picker v-model="formData.end_date" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" />
      </el-form-item>
      <el-form-item label="是否工作日">
        <el-switch
          v-model="formData.is_workday"
          :active-value="1"
          :inactive-value="0"
          active-text="工作日"
          inactive-text="休息日"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确认</el-button>
    </template>
  </el-dialog>
</template>
